package com.ruoyi.biz.service;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.biz.model.dto.BizProjectTeamDto;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.biz.mapper.BizProjectTeamMapper;
import com.ruoyi.biz.domain.BizProjectTeam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


/**
 * 项目团队成员Service业务层处理
 *
 * @author tianl
 * @date 2025-01-22
 */
@Service
public class BizProjectTeamService extends ServiceImpl<BizProjectTeamMapper, BizProjectTeam> {

    /**
     * 分页查询项目团队成员
     */
    public IPage<BizProjectTeam> listPage(BizProjectTeam req) {
        return baseMapper.list(PageUtils.page(), req);
    }

    /**
     * 查询项目团队成员列表
     */
    public List<BizProjectTeam> list(BizProjectTeam req) {
        return baseMapper.list(req);
    }

    /**
     * 根据ID查询
     */
    public BizProjectTeam selectById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 新增修改项目团队成员
     */
    @Transactional(rollbackFor = Exception.class)
    public void beforeSave(BizProjectTeamDto dto) {
        LambdaQueryWrapper<BizProjectTeam> wrapper = new LambdaQueryWrapper<BizProjectTeam>();
        wrapper.and(i -> i.eq(BizProjectTeam::getProjectId, dto.getProjectId()));
        List<BizProjectTeam> list = this.list(wrapper);
        List<Long> userIds = list.stream().map(BizProjectTeam::getUserId).collect(Collectors.toList());
        for (Long userId : dto.getUserIds()) {
            if (userIds.contains(userId)) {
                continue;
            }
            BizProjectTeam team = new BizProjectTeam();
            team.setUserId(userId);
            team.setProjectId(dto.getProjectId());
            team.setCreateTime(DateUtils.getNowDate());
            team.setUpdateTime(DateUtils.getNowDate());
            this.save(team);
        }
    }

    /**
     * 批量删除项目团队成员
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }

}
